/*

Copyright 2009 Michel Boto. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#pragma once
#include "Base.h"
#include "ChildIteratorHolder.h"
#include <stack>

namespace Blatt
{

template <class DerivedType, class NodeType, class ChildIteratorType>
class InOrder : public Base<DerivedType,NodeType>
{
public:

	InOrder()
	: Base<DerivedType,NodeType>()
	{}
	
	InOrder( NodeType& rootNode )
	: Base<DerivedType,NodeType>( rootNode )
	{
		increment(); // initialize the stack with the first childit range and parent
	}
	
protected:

	// in order to be as flexible as possible with the other iterators, even though we're deriving here
	// let's make its constructor as compatible as we can with the base, so that nobody has to change much
	// existing code if they want to switch iterators
	struct ChildItAndParent : public ChildIteratorHolder<ChildIteratorType>
	{
		ChildItAndParent( const ChildIteratorType current, const ChildIteratorType end )
		: ChildIteratorHolder<ChildIteratorType>( current, end )
		, _parent(0)
		, _pos(0)
		{}
		
		ChildItAndParent( const ChildItAndParent& other, NodeType* parent )
		: ChildIteratorHolder<ChildIteratorType>( other._current, other._end )
		, _parent( parent )
		, _pos( 0 )
		{
		}
		
		bool operator==( const ChildItAndParent& other ) const
		{
			return (static_cast<const ChildIteratorHolder<ChildIteratorType>&>(*this) == static_cast<const ChildIteratorHolder<ChildIteratorType>&>(other))
				&& (_parent == other._parent) 
				&& (_pos == other._pos);
		}
		
		NodeType* _parent;
		size_t _pos;
	};

	typedef ChildItAndParent TChildItHolder;
	
private:

	std::stack<TChildItHolder> _currentChildStack;
	
	friend class boost::iterator_core_access;
	
	bool equal( const InOrder& other ) const
	{
		if ( other.GetRootNode() == Base<DerivedType,NodeType>::GetRootNode() )
		{
			if ( _currentChildStack.empty() )
				return other._currentChildStack.empty();
			if ( !other._currentChildStack.empty() )
				return _currentChildStack.top() == other._currentChildStack.top();
		}
		return false;
	}
	
	void findLeftMostNodeRange()
	{
		NodeType* startWithNode = _currentChildStack.empty() ? Base<DerivedType,NodeType>::GetRootNode() : &(*_currentChildStack.top()._current);
		// find the leftmost node range (i.e. the one whose first child has no children)
		while ( startWithNode ) {
			TChildItHolder childRange( static_cast<DerivedType*>(this)->GetChildRangeForNode( *startWithNode ), startWithNode );
			if ( childRange._current == childRange._end )
			{
				return;
			}
			startWithNode = &(*childRange._current);
			_currentChildStack.push( childRange );
		}
	}
	
	NodeType& dereference() const
	{
		const TChildItHolder& currentChildRange = _currentChildStack.top();
		return currentChildRange._pos == 1 ? *currentChildRange._parent : *currentChildRange._current;
		
	}

	void increment()
	{		
		if ( _currentChildStack.empty() ) {
			findLeftMostNodeRange();
		} else {
			TChildItHolder& currentChildRange = _currentChildStack.top();
			if ( currentChildRange._current == currentChildRange._end )
			{
				std::cout << "+";
			} else
			{
				if ( currentChildRange._pos == 1 ) {
					currentChildRange._parent = 0;
					findLeftMostNodeRange();
				} else {
					++currentChildRange._current;
					if ( currentChildRange._current == currentChildRange._end )
					{
						std::cout << ".";
						_currentChildStack.pop();
						while ( !_currentChildStack.empty() )
						{
							TChildItHolder& rangeAboveCurrent = _currentChildStack.top();
							if ( rangeAboveCurrent._current != rangeAboveCurrent._end )
							{
								std::cout << "?";
								++rangeAboveCurrent._current;
							}
							if ( rangeAboveCurrent._current == rangeAboveCurrent._end )
								_currentChildStack.pop();
							else
							{
								if ( rangeAboveCurrent._pos == 1 )
								{
									rangeAboveCurrent._parent = 0;
									findLeftMostNodeRange();
								}
								else
									++rangeAboveCurrent._pos;
								break;
							}
						}
					}
				}
				++currentChildRange._pos;
			}
		}
		if ( _currentChildStack.empty() )
			Base<DerivedType,NodeType>::ClearRootNode();
	}


};

}